import fs from 'fs';
import path from 'path';
import imageType from 'image-type';
import optipng from './codecs/optipng';
import mozjpeg from './codecs/mozjpeg';
import { traversalFile, filterExtName } from './util';


async function compress(filePath: string) {
    let buffer = fs.readFileSync(filePath);
    let type = imageType(buffer);
    let uint8: Uint8Array;
    switch (type.mime) {
        case optipng.mimeType:
            uint8 = await optipng.encode(buffer);
            break;
        case mozjpeg.mimeType:
            uint8 = await mozjpeg.encode(buffer);
            break;
    }
    if (uint8)
        fs.writeFileSync(filePath, uint8);
}



(async () => {

    let allFile = traversalFile(path.join(__dirname, '../res'));
    let imgFile = filterExtName(allFile, [optipng.extension, mozjpeg.extension]);
    let length = imgFile.length;
    for (let i = 0; i < length; i++) {
        console.log(`当前: ${i + 1} / ${length}`);
        await compress(imgFile[i]);
    }

})();